package cece.controller;

import cece.entity.User;
import cece.service.UserService;
import cece.utils.RedisUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * 用户控制层接口
 */
@RestController
public class UserController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserService userService;

    @RequestMapping("/user/getCode")
    @ResponseBody
    public String getCode(@RequestParam String telephone) {
        String result = userService.getCode(telephone);
        if ("success".equals(result)) {
            return "success";
        }
        return "fail";
    }

    @RequestMapping("/user/userRegister")
    @ResponseBody
    public String register(@RequestBody User user) {
        String redisCode = (String) redisUtils.get(user.getTelephone());
        System.out.println(redisCode);
        if (!redisCode.equals(user.getCode())) {
            return "codefail";
        }
        boolean result = userService.userRegister(user);
        if (result) {
            return "success";
        }
        return "fail";
    }

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public User login(@RequestBody User user) {
        // 使用用户的登录信息创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPassword());
        // 主体
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        System.out.println(loginUser);
        return loginUser;
    }
}
